package com.controller;
import com.dao.MsgDao;
import com.dao.SubscribeDao;
import com.dao.UserDao;
import com.pojo.Msg;
import com.pojo.Result;
import com.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import static com.utils.MessageUtils.*;

@RestController
@RequestMapping("/subscribe")
public class SubscribeController {

    @Autowired
    private SubscribeDao subscribeDao;

    @Autowired
    private MsgDao msgDao;

    @Autowired
    private UserDao userDao;

    @PostMapping("/{id}")
    public Result subscribe(@PathVariable int id,HttpServletRequest request){
        Msg msg = new Msg();
        String userId = request.getSession().getAttribute("user").toString();
        String userNickName = userDao.getBYIdOrEMail(userId).getNickName();
        String nickName = userDao.getBYIdOrEMail(String.valueOf(id)).getNickName();
        msg.setSender(userNickName);
        msg.setReceiver(nickName);
        String time = DateUtils.now();
        msg.setMessage("用户"+userNickName+"订阅了你");
        msg.setTime(time);
        subscribeDao.add(Integer.parseInt(userId),id);
        msgDao.add(msg);
        return Result.success(SUBSCRIBE_SUCCESS);
    }

    @DeleteMapping("/{id}")
    public Result cancelSubscribe(@PathVariable int id,HttpServletRequest request){
        String userId = request.getSession().getAttribute("user").toString();
        subscribeDao.delete(Integer.parseInt(userId),id);
        return Result.success(CANCEL_SUBSCRIBE_SUCCESS);
    }
}
